package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.config.BigDataConfig;
import com.ruoyi.common.config.FtpConfig;
import com.ruoyi.common.core.domain.JSONObjectPro;
import com.ruoyi.common.enums.OrderNameEnum;
import com.ruoyi.common.enums.comlbs.DataDictTypeEnum;
import com.ruoyi.common.exception.BigDataException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SnowFlakeIDGenerator;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.CommonResponse;
import com.ruoyi.common.utils.http.HttpRequest;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.request.driver.DriverFaceSendParam;
import com.ruoyi.system.domain.request.driver.DriverFaceSendRecordParam;
import com.ruoyi.system.domain.vo.order.FaceSendInfo;
import com.ruoyi.system.mapper.DriverInfoMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.ComLbsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.SecurityUtils.getUserId;
import static com.ruoyi.common.utils.SecurityUtils.getUsername;

/**
 * 驾驶员信息Service业务层处理
 * 
 * @author wp
 * @date 2023-08-10
 */
@Service
public class DriverInfoServiceImpl extends ServiceImpl<DriverInfoMapper, DriverInfo> implements IDriverInfoService {

    @Autowired
    private DriverInfoMapper driverInfoMapper;

    @Autowired
    private IDriverEquipmentService driverEquipmentService;

    @Autowired
    private IOrderConfigurationService orderConfigurationService;

    @Autowired
    private IOrderSendRecordService orderSendRecordService;

    @Autowired
    private IVehicleManagementService vehicleManagementService;

    @Autowired
    private BigDataConfig bigDataConfig;

    @Autowired
    private FtpConfig ftpConfig;

    @Override
    public DriverInfo selectOne(Long id) {
        return driverInfoMapper.get(id);
    }

    /**
     * 查询驾驶员信息列表
     * 
     * @param driverInfo 驾驶员信息
     * @return 驾驶员信息
     */
    @DataScope
    @Override
    public List<DriverInfo> selectList(DriverInfo driverInfo) {
        return driverInfoMapper.list(driverInfo);
    }

    /**
     * 修改驾驶员信息
     * 
     * @param driverInfo 驾驶员信息
     * @return 结果
     */
    @Override
    public boolean updateDriverInfo(DriverInfo driverInfo) {
        DriverInfo oldDriver = getById(driverInfo.getId());
        //已绑定设备的负责人无法修改所属公司
        int count = driverEquipmentService.count(new QueryWrapper<DriverEquipment>().eq("driver_id", driverInfo.getId()));
        if (count > 0 && !oldDriver.getCompanyId().equals(driverInfo.getCompanyId())) {
            //删除新增的文件
            ComLbsUtils.exceptionFileHandle(oldDriver.getPicture(), driverInfo.getPicture(), true);
            throw new ServiceException("此负责人已绑定设备，无法修改所属公司！");
        }
        //图片处理
        ComLbsUtils.fileHandle(oldDriver.getPicture(), driverInfo.getPicture(), true);
        return updateById(driverInfo);
    }

    @Override
    public void deleteDriverInfo(Long[] ids) {
        for (Long id : ids) {
            deleteDriverInfo(id);
        }
    }

    @Override
    public void deleteDriverInfo(Long id) {
        int count = driverEquipmentService.count(new QueryWrapper<DriverEquipment>().eq("driver_id", id));
        if (count > 0) throw new ServiceException("操作失败，此负责人正在使用中！");
        //删除图片
        ComLbsUtils.fileHandle(getById(id).getPicture(), new ArrayList<>(), true);
        //删除负责人
        removeById(id);
    }

    /**
     * 根据设备ID获取所有驾驶员名字组
     * @param equipmentId
     * @return
     */
    @Override
    public String getNameGroupByEquipmentId(Long equipmentId) {
        return driverInfoMapper.getNameGroupByEquipmentId(equipmentId);
    }

    /**
     * 下发人脸照片
     */
    @Override
    public void sendFace(DriverFaceSendParam param){
        OrderConfiguration orderConfig = orderConfigurationService.getOne(new QueryWrapper<OrderConfiguration>()
                .eq("order_type", OrderNameEnum.DRIVER_FACE.getCode()));
        if (orderConfig == null) throw new ServiceException("下发人脸指令不存在");
        String deviceNo = param.getDeviceId();
        if (StringUtils.isEmpty(deviceNo)) throw new ServiceException("该监管对象未绑定设备");
        List<DriverFaceSendParam.DriverInfo> list = param.getList();
        if (CollectionUtils.isEmpty(list)) throw new ServiceException("请选择下发对象");
        OrderConfiguration orderConfiguration = new OrderConfiguration().setOrderType(OrderNameEnum.DRIVER_FACE.getCode());
        List<OrderConfiguration> orderConfigurationList = orderConfigurationService.selectList(orderConfiguration);
        Long orderId = null;
        if (!CollectionUtils.isEmpty(orderConfigurationList)) {
            orderId = orderConfigurationList.get(0).getId();
        }
        List<FaceSendInfo> faceInfo = new ArrayList<>();
        //从业资格证
        String jobSeniorityCard = "123";

        for (DriverFaceSendParam.DriverInfo driverFaceSendDO : list) {
            FaceSendInfo faceSendInfo = new FaceSendInfo();
            //照片id（司机身份证号）
            faceSendInfo.setDriverId(driverFaceSendDO.getIdCard());
            //司机名
            faceSendInfo.setDriverName(driverFaceSendDO.getDriverName());
            //人脸图片地址
            faceSendInfo.setFacePictureUrl(ftpConfig.getFacePicUrl() + driverFaceSendDO.getFacePictureUrl());
            faceSendInfo.setFacePictureId(driverFaceSendDO.getDriverId());
            faceSendInfo.setJobSeniorityCard(jobSeniorityCard);
            faceSendInfo.setFacePictureAgreement(ftpConfig.getFacePicAgreement());
            faceSendInfo.setFtpAccount(ftpConfig.getUsername());
            faceSendInfo.setFtpPassword(ftpConfig.getPassword());
            faceInfo.add(faceSendInfo);
        }

        JSONObjectPro content = new JSONObjectPro()
                .put("distributeMsgTopic", OrderNameEnum.DRIVER_FACE.getCode())
                .put("response", ftpConfig.getResponse())
                .put("userId", getUserId())
                .put("username", getUsername())
                .put("distributeTime", DateUtils.getTime())
                .put("devNo", deviceNo)
                .put("requestId", System.currentTimeMillis())
                .put("Type", 0)
                .put("faceInfoList", faceInfo);
        Long id = SnowFlakeIDGenerator.getInstance().nextId();
        JSONObjectPro params = new JSONObjectPro()
                .put("id", id)
                .put("content", JSONObject.toJSONString(content));

        CommonResponse<Object> response = HttpRequest.postJson(bigDataConfig.getGatewayApiUrl() + "/KafkaApiController/distributeAll", params, Object.class);
        if (!response.isSuccess()) throw new BigDataException("发送失败！");
        else {
            // 指令下发记录存了之后没法展示
            List<OrderSendRecord> orderSendRecordList = new ArrayList<>();
            //同一组指令记录的groupId相同
            Long groupId = System.currentTimeMillis();
            OrderSendRecord orderSendRecord = new OrderSendRecord();
            orderSendRecord.setId(id);
            orderSendRecord.setOrderId(orderId);
            orderSendRecord.setContent(content);
            VehicleManagement vehicleIdAndNumberPlate = vehicleManagementService.getVehicleIdAndNumberPlate(deviceNo);
            orderSendRecord.setDeviceNo(deviceNo);
            orderSendRecord.setVehicleNum(vehicleIdAndNumberPlate.getNumberPlate());
            orderSendRecord.setVehicleId(vehicleIdAndNumberPlate.getId());
            orderSendRecord.setStatus(0);
            orderSendRecord.setGroupId(groupId);
            orderSendRecord.setCreateTime(new Date());
            orderSendRecord.setCreateBy(getUserId().toString());
            orderSendRecordList.add(orderSendRecord);
            orderSendRecordService.saveBatch(orderSendRecordList);
        }
    }

    /**
     * 人脸识别指令下发记录
     */
    @Override
    public List<OrderSendRecord> driverFaceSendRecord(DriverFaceSendRecordParam param) {
        if (param.getVehicleId() == null) throw new ServiceException("请选择监管对象");
        OrderSendRecord orderSendRecord = new OrderSendRecord()
                .setStartTime(param.getStartTime())
                .setEndTime(param.getEndTime())
                .setVehicleId(param.getVehicleId())
                .setOrderType(OrderNameEnum.DRIVER_FACE.getCode());
        List<OrderSendRecord> list = orderSendRecordService.list(orderSendRecord);
        Map<Long, String> driverIdNameMap = driverInfoMapper.list(new DriverInfo()).stream().collect(Collectors.toMap(DriverInfo::getId, DriverInfo::getName));
        list.forEach(x -> {
            x.setStatusName(DictUtils.getDictLabel(DataDictTypeEnum.ORDER_SEND_STATUS.getText(), x.getStatus()));
            if (StringUtils.isNotEmpty(x.getResponseValue())) {
                List<String> idWithResult = Arrays.asList(x.getResponseValue().substring(1, x.getResponseValue().length() - 1).split(", "));
                List<String> result = new ArrayList<>();
                idWithResult.forEach(d -> {
                    if (StringUtils.isNotEmpty(d)) {
                        String[] split = d.split(":");
                        Long id = Long.parseLong(split[0]);
                        String name = driverIdNameMap.get(id);
                        result.add(name == null ? "未知" : name + ":" + split[1]);
                    }
                });
                x.setResponseValue(result.toString());
            }
        });
        return list;
    }
}
